//
//  Ex+Array.swift
//  Smoothly
//
//  Created by jh on 2023/12/7.
//

import Foundation

extension Array {    
    /// 数组分组
    func boomMap(number: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: number).map {
                Array(self[$0 ..< Swift.min($0 + number, count)])
            }
    }
    
    func chunked(into size: Int) -> [[Element]] {
        stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
    
    /// 数组分组
    func stepArr(page: Int, step: Int) -> [Element] {
        let currPage = page * step
        
        if currPage + step < count {
            return Array(self[currPage..<(currPage + step)])
        } else if currPage < count {
            return Array(self[currPage..<count])
        } else {
            return []
        }
    }
    
    func element(at index: Int) -> Element? {
        index >= 0 && index < endIndex ? self[index] : nil
    }
}

extension Array where Element: Identifiable {
    /// 数组分组
    func strideBy(_ step: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: 3).map {
            if ($0 + step) > self.count {
                return Array(self[$0...])
            } else {
                return Array(self[$0..<$0+step])
            }
        }
    }
}

extension RandomAccessCollection where Self.Element: Identifiable {
    // 来源：https://juejin.cn/post/6844904053114142728
    func isLastItem<Item: Identifiable>(_ item: Item) -> Bool {
        guard !isEmpty else {
            return false
        }
        
        // 查找当前item索引
        // RandomAccessCollection能够以O(1)复杂度查找元素非常快
        guard let itemIndex = firstIndex(where: { $0.id.hashValue == item.id.hashValue }) else {
            return false
        }
        
        // 比较当前item索引和结束索引endIndex(结束索引等于当前数组item的数量)，如果距离是1。代表当前item就是最后一个
        let distance = self.distance(from: itemIndex, to: endIndex)
        return distance == 1
    }
}
